﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DACU.Player;
using DACU.Player.Enums;
using DACU.Tools;
using Un4seen.Bass;

namespace DACU.UserControls.Player
{
	/// <summary>
	/// Логика взаимодействия для PlayerControl.xaml
	/// </summary>
	public partial class PlayerControl : INotifyPropertyChanged
	{
		public event EventHandler TrackChanged;
		public event PropertyChangedEventHandler PropertyChanged;

		MediaPlayer mp = new MediaPlayer();

		private string _title;
		public string Title
		{
			get { return _title; }
			set
			{
				_title = value;
				if(PropertyChanged!=null)
					PropertyChanged(this,new PropertyChangedEventArgs("Title"));
			}
		}

		public Window OwnerWindow { get; set; }

		public PlayerControl()
		{
			Initialize();
		}

		public PlayerControl(Window owner)
		{
			OwnerWindow = owner;
			Initialize();
		}

		void Initialize()
		{
			InitializeComponent();
			TrackChanged += PlayerWindow_TrackChanged;
			mp.ChangedSecondsPos += playerNavigation1.MpChangedPost;
			mp.DownloadStateChanged += playerNavigation1.ChangeDownloadProgress;
			mp.TrackEnded += mp_TrackEnded;
			mp.ActivityChanged += playerNavigation1.MpActivityChanged;
			mp.ActivityChanged += playList1.MpActivityChanged;
			mp.Volume = playerNavigation1.Volume = ConfigTools.ConfigFile.Volume; //Properties.Settings.Default.Volume;
			if (!String.IsNullOrWhiteSpace(ConfigTools.ConfigFile.Playlist.LastPlayList) && File.Exists(ConfigTools.ConfigFile.Playlist.LastPlayList))
				playList1.Load(ConfigTools.ConfigFile.Playlist.LastPlayList);
			if (ConfigTools.ConfigFile.Playlist.Track.LastTrackType == TrackType.File &&
				ConfigTools.ConfigFile.Playlist.Track.LastState == BASSActive.BASS_ACTIVE_PLAYING &&
				ConfigTools.ConfigFile.Playlist.Track.Id > -1 &&
				ConfigTools.ConfigFile.Playlist.Track.LastPosition > -1)
			{
				playList1.PlayIndex(ConfigTools.ConfigFile.Playlist.Track.Id);
				mp.SetPosition(ConfigTools.ConfigFile.Playlist.Track.LastPosition);
			}
			playerNavigation1.PositionChanged += mp.SetPosition;
			DataContext = playList1;
		}

		void mp_TrackEnded(object sender, EventArgs e)
		{
			PlayNext(sender, e);
		}

		void PlayNext(object sender, EventArgs e)
		{
			Track audio = playList1.NextTrack();
			if (audio == null || audio.IsEmpty)
			{
				//mp.PlayNext("", true);
				mp.PlayNextTrack(null, true);
				return;
			}
			//mp.PlayNext(audio.Path);
			mp.PlayNextTrack(audio);
			if (TrackChanged != null)
				TrackChanged(sender, e);
		}

		void PlayerWindow_TrackChanged(object sender, EventArgs e)
		{
			playList1.Dispatcher.Invoke(new Action(delegate
			{
				if (playList1.CurrentTrack != null)
				{
					playerNavigation1.TrackArtist = (playList1.CurrentTrack.Artist ?? "").Trim();
					playerNavigation1.TrackTitle = (playList1.CurrentTrack.Title ?? "").Trim();
					playerNavigation1.IsPositionEnabled = (playList1.CurrentTrack??new Track()).Type != TrackType.Url;
					//Title = (playList1.SelectedItem.Artist ?? "").Trim() + " - " +
					//        (playList1.SelectedItem.Title ?? "").Trim() + " (" +
					//        playList1.SelectedItem.Duration + ")";
				}
			}));
			playerNavigation1.TrackLength = mp.GetSecondsLength();
		}

		public void SetPlayList(IEnumerable playlist)
		{
			playList1.Source = playlist;
		}

		private void playerNavigation1_VolumeChanged(float persent)
		{
			mp.Volume = persent;
		}

		private void playerNavigation1_PrevTrigered(object sender, EventArgs e)
		{
			Track audio = playList1.PrevTrack();
			if (audio == null || audio.IsEmpty)
			{
				//mp.PlayNext("", true);
				mp.PlayNextTrack(null, true);
				return;
			}
			//mp.PlayNext(audio.Path);
			mp.PlayNextTrack(audio);
			if (TrackChanged != null)
				TrackChanged(sender, e);
		}

		private void playerNavigation1_NextTrigered(object sender, EventArgs e)
		{
			PlayNext(sender, e);
		}

		private void playerNavigation1_PlayPauseTrigered(object sender, EventArgs e)
		{
			mp.PauseSong();
		}

		private void playerNavigation1_StopTrigered(object sender, EventArgs e)
		{
			mp.StopSong();
		}

		private void playList1_TrackChanged(Track track)
		{
			if (track!=null && !track.IsEmpty)
			{
				mp.PlayNextTrack(track);
				if (TrackChanged != null)
					TrackChanged(playList1, new EventArgs());
				return;
			}
			//mp.PlayNext("", true);
			mp.PlayNextTrack(null, true);
		}

		//private void playList1_TrackChanged(string newSongUrl)
		//{
		//    if (!String.IsNullOrWhiteSpace(newSongUrl))
		//    {
		//        mp.PlayNext(newSongUrl);
		//        if (TrackChanged != null)
		//            TrackChanged(playList1, new EventArgs());
		//        return;
		//    }
		//    //mp.PlayNext("", true);
		//    mp.PlayNext(null, true);
		//}

		public void WindowClosing()
		{
			ConfigTools.ConfigFile.Playlist.LastPlayList = playList1.CurrentFileListPath;
			ConfigTools.ConfigFile.Playlist.Track.Id = playList1.CurrentTrackId;
			ConfigTools.ConfigFile.Playlist.Track.LastPosition = mp.GetSecondsPosition();
			ConfigTools.ConfigFile.Playlist.Track.LastState = mp.Activity;
			if (playList1.CurrentTrack != null)
				ConfigTools.ConfigFile.Playlist.Track.LastTrackType = playList1.CurrentTrack.Type;
			playList1.Save();
			if (mp.Handle != 0)
				mp.Free();
			playList1.Clear();
			TrackChanged -= PlayerWindow_TrackChanged;
			mp.ChangedSecondsPos -= playerNavigation1.MpChangedPost;
			mp.TrackEnded -= mp_TrackEnded;
			mp.ActivityChanged -= playerNavigation1.MpActivityChanged;
			mp.ActivityChanged -= playList1.MpActivityChanged;
			playerNavigation1.PositionChanged -= mp.SetPosition;
			//Properties.Settings.Default.FileLoop = playList1.IsFileLoop;
			//Properties.Settings.Default.Shuffle = playList1.IsShuffle;
			//Properties.Settings.Default.ListLoop = playList1.IsListLoop;
			//Properties.Settings.Default.Save();
			ConfigTools.ConfigFile.IsFileLoop = playList1.IsFileLoop;
			ConfigTools.ConfigFile.IsListLoop = playList1.IsListLoop;
			ConfigTools.ConfigFile.IsShuffle = playList1.IsShuffle;
			ConfigTools.SaveConfig();
		}
	}
}
